<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" :style="isWidth ? 'width:99%' : ''">
    <div>
      <div class="" v-for="item in listData" :key="item.id">
        <p style="background-color: #fafafa; padding: 4px 4px; font-weight: bold">{{
          item.groupName
        }}</p>
        <el-check-tag
          v-for="tag in item.tags"
          :key="tag.id"
          @click="setlabelList(tag)"
          style="margin-right: 4px"
          :style="
            tag.checked ? { marginRight: '4px', color: '#ffffff', backgroundColor: '#0052cc' } : ''
          "
          class="mb-4px inline-block"
          >{{ tag.name }}</el-check-tag
        >
      </div>
      <el-divider></el-divider>
      <p>当前标签</p>
      <el-tag
        :style="{ marginRight: '4px' }"
        v-for="(init, index) in formData.tags"
        closable
        @close="closeTags(init, index)"
        :key="init.id"
        class="mb-4px"
        >{{ init.name || init.tagName }}</el-tag
      >
    </div>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as MomentLogApi from '@/api/wecom/momentlog'

import * as customerApi from '@/api/wecom/customer/index'
import { number } from 'vue-types'

const props = defineProps({
  customerObj: Object,
  isWidth: {
    type: Boolean,
    default: false
  }
})
defineOptions({ name: 'EditTagFrom' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('编辑标签') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('update') // 表单的类型：create - 新增；update - 修改

const formData = ref({
  tags: [],
  originalArray: []
})

/** 打开弹窗 */
const open = async (id?: number, tags?: Array) => {
  dialogVisible.value = true
  resetForm()
  formData.value.tags = JSON.parse(JSON.stringify(tags))
  formData.value.originalArray = JSON.parse(JSON.stringify(tags))
  getTagList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success', 'setlabelList']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    let obj
    if (formType.value === 'update') {
      if (formData.value.originalArray.length == 0) {
        obj = {
          userId:
            props.customerObj.followUserList[props.customerObj.followUserList.length - 1].qwUserId,
          externalUserId: props.customerObj.externalUserId,
          addTag: formData.value.tags.map((item) => item.tagId)
        }
      } else {
        let arr = formData.value.originalArray.map((item) => item.tagId) //原始
        let tags = formData.value.tags.map((item) => item.tagId) //现在
        let addTag = []
        let removeTag = []
        tags.map((item) => {
          if (arr.indexOf(item) == -1) {
            addTag.push(item)
          }
        })
        arr.map((item) => {
          if (tags.indexOf(item) == -1) {
            removeTag.push(item)
          }
        })
        obj = {
          userId:
            props.customerObj.followUserList[props.customerObj.followUserList.length - 1].qwUserId,
          externalUserId: props.customerObj.externalUserId,
          addTag: addTag,
          removeTag: removeTag
        }
      }
      if (obj.addTag.length == 0 && obj.removeTag.length == 0) {
        message.warning('无数据变动,无需修改!')
        return
      }
      await customerApi.editCustomerTag(obj)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    tags: [],
    originalArray: []
  }
}

const listData = ref([])
/** 标签查询列表 */
const getTagList = async () => {
  try {
    let list = await MomentLogApi.treeList()
    if (formData.value.tags.length) {
      list.forEach((items) => {
        items.tags.forEach((item) => {
          let check = formData.value.tags.find((init) => init.tagId == item.tagId)
          if (check) {
            item.checked = true
          } else {
            item.checked = false
          }
        })
      })
    } else {
      list.forEach((items) => {
        items.tags.forEach((item) => {
          item.checked = false
        })
      })
    }
    listData.value = list
  } finally {
  }
}
/*用户添加取消*/
const setlabelList = (tag) => {
  let tags = formData.value.tags.find((item) => item.tagId == tag.tagId)
  if (tags) {
    listData.value.forEach((item) => {
      item.tags.forEach((element) => {
        if (element.tagId == tag.tagId) {
          let indexs
          formData.value.tags.forEach((its, index) => {
            if (its.tagId == tags.tagId) {
              indexs = index
            }
          })
          formData.value.tags.splice(indexs, 1)
          element.checked = false
        }
      })
    })
  } else {
    listData.value.forEach((item) => {
      item.tags.forEach((element) => {
        if (element.tagId == tag.tagId) {
          formData.value.tags.push(element)
          element.checked = true
        }
      })
    })
  }
}
/*操作标签*/
const closeTags = (tag, index) => {
  listData.value.forEach((item) => {
    item.tags.forEach((element) => {
      if (element.tagId == tag.tagId) {
        formData.value.tags.splice(index, 1)
        element.checked = false
      }
    })
  })
}
</script>
<style scoped>
::v-deep(.el-check-tag) {
  padding: 6px 9px;
  font-size: 12px;
}
::v-deep(.el-tag) {
  height: 26px;
  line-height: 26px;
  font-size: 12px;
  border: none;
}
</style>
